package org.zn.note.designpattern;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式（Observer Pattern）
 * <p>
 * 可以用jdk自带:
 * 主题 {@link java.util.Observable}  (缺点是一个类，只能继承)
 * 观察者 {@link java.util.Observer#update(java.util.Observable, Object)}  收到通知时可以获得主题对象，和主题发送的一个Object定制对象
 * <p>
 * 例子{@link ObserverByJdk}
 * <p>
 * 观察者可以收到主题对象本身，还可以收到主题对象发送的一个Object
 * 所以数据可以是存在主题对象中，然后观察者去“拉”
 * 也可以使主题直接将数据存在Object里，“推”给观察者
 */
public class Pattern20_Observer {

    public static void main(String[] args) {
        // 有一个主题
        Subject subject = new Subject();
        // 3个订阅者(观察者)
        new BinaryObserver(subject);
        new OctalObserver(subject);
        new HexaObserver(subject);
        // 主题状态开始变化
        System.out.println("First state change: 15");
        subject.setState(15);
        System.out.println("Second state change: 10");
        subject.setState(10);

        // jdk 自带的Observer
        System.out.println("---------- JDK 自带Observer的例子 -----------");
        ObserverByJdk.run();
    }

    // 主题：都可以订阅主题，主题状态变化会通知订阅者(观察者)
    private static class Subject {

        private List<Observer> observers
                = new ArrayList<Observer>();

        private int state;

        int getState() {
            return state;
        }

        void setState(int state) {
            this.state = state;
            notifyAllObservers();
        }

        void attach(Observer observer) {
            observers.add(observer);
        }

        void notifyAllObservers() {
            for (Observer observer : observers) {
                observer.update();
            }
        }
    }

    private static abstract class Observer {
        Subject subject;

        abstract void update();
    }

    private static class BinaryObserver extends Observer {
        BinaryObserver(Subject subject) {
            this.subject = subject;
            this.subject.attach(this);
        }

        @Override
        public void update() {
            System.out.println("Binary String: "
                    + Integer.toBinaryString(subject.getState()));
        }
    }

    private static class OctalObserver extends Observer {
        OctalObserver(Subject subject) {
            this.subject = subject;
            this.subject.attach(this);
        }

        @Override
        public void update() {
            System.out.println("Octal String: "
                    + Integer.toOctalString(subject.getState()));
        }
    }

    private static class HexaObserver extends Observer {
        HexaObserver(Subject subject) {
            this.subject = subject;
            this.subject.attach(this);
        }

        @Override
        public void update() {
            System.out.println("Hex String: "
                    + Integer.toHexString(subject.getState()).toUpperCase());
        }
    }

    // 用jdk自带的观察者
    private static class ObserverByJdk {

        static void run() {
            Weather weather = new Weather();
            new WeatherDisplay1(weather);
            new WeatherDisplay1(weather);
            new WeatherDisplay2(weather);
            weather.run();
        }

        // 定义主题subject
        private static class Weather extends java.util.Observable {
            private String weather;

            void run() {
                // 天气变化
                weather = "刮风";
                setChanged();
                notifyObservers("刮风啦！");
                weather = "下雨";
                setChanged();
                notifyObservers("下雨啦！");
            }
        }

        // 定义观察者1
        private static class WeatherDisplay1 implements java.util.Observer {
            // 创建观察者时，将自己加入到主题的通知队列中
            WeatherDisplay1(java.util.Observable subject) {
                subject.addObserver(this);
            }

            @Override
            public void update(java.util.Observable o, Object arg) {
                System.out.printf("[%s:display1] [%s] [%s] \n", this.hashCode(), ((Weather) o).weather, arg);
            }
        }

        // 定义观察者2
        private static class WeatherDisplay2 implements java.util.Observer {
            WeatherDisplay2(java.util.Observable subject) {
                subject.addObserver(this);
            }

            @Override
            public void update(java.util.Observable o, Object arg) {
                System.out.printf("[%s:display2] [%s] [%s] \n", this.hashCode(), ((Weather) o).weather, arg);
            }
        }
    }
}
